<?php

namespace App\Admin\Forms\Aliyun;

use App\Models\Aliyun;
use Dcat\Admin\Contracts\LazyRenderable;
use Dcat\Admin\Exception\RuntimeException;
use Dcat\Admin\Http\JsonResponse;
use Dcat\Admin\Traits\LazyWidget;
use Dcat\Admin\Widgets\Form;
use OSS\Core\OssException;
use OSS\Http\RequestCore_Exception;
use OSS\Model\WebsiteConfig;
use OSS\OssClient;

class CreateOssBucketForm extends Form implements LazyRenderable
{
    use LazyWidget;

    /**
     * @throws OssException
     * @throws RequestCore_Exception
     */
    public function handle(array $input): JsonResponse
    {
        $aliyun = Aliyun::ofAdmin()->find($input['aliyun_id']);

        $ossClient = new OssClient($aliyun->app_id, $aliyun->app_secret, 'https://oss-cn-beijing.aliyuncs.com');

        $ossClient->createBucket($input['bucket'], OssClient::OSS_ACL_TYPE_PUBLIC_READ);

        if ($input['is_website']) {
            $websiteConfig = new WebsiteConfig('index.html', 'index.html');
            $ossClient->putBucketWebsite($input['bucket'], $websiteConfig);
        }

        return $this->response()->success('$message')->refresh();
    }

    /**
     * @throws RuntimeException
     */
    public function form(): void
    {
        $this->select('aliyun_id', '云账户')
            ->required()
            ->options(Aliyun::ofAdmin()->pluck('name', 'id'))
            ->help('创建Bucket后，才能在控制台中新增存储，应用在系统内');
        $this->text('bucket', '桶名称')
            ->required()
            ->help('命名长度为 3~63 个字符，只允许小写字母、数字、短横线（-）<br/>且不能以短横线开头或结尾<br/>Bucket 名称在 OSS 范围内必须全局唯一<br/>目前使用的OSS统一为【北京地域】');
        $this->switch('is_website', '网页托管')
            ->help('只有网页托管的OSS，才能上传版本并绑定域名访问，非网页托管的OSS只能进行存储使用。')
            ->default(false);
    }
}
